package com.roadjava.rbac.security.handler;


import com.roadjava.rbac.bean.dto.SecurityUserDTO;
import com.roadjava.rbac.bean.dto.TokenDTO;
import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.bean.vo.LoginResultVO;

import com.roadjava.rbac.config.HoneyLogs;
import com.roadjava.rbac.enums.LogEnum;
import com.roadjava.rbac.manager.CacheManager;
import com.roadjava.rbac.security.LoginAttemptService;
import com.roadjava.rbac.util.ConvertUtil;
import com.roadjava.rbac.util.JwtUtil;
import com.roadjava.rbac.util.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功之后的处理
 * @author zhaodaowen
 *
 */

@Component

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Resource
    private CacheManager cacheManager;
    @Resource
    private LoginAttemptService loginAttemptService;
    // 注入
    @Override

    @HoneyLogs(operation = "登录",type = LogEnum.LOGIN)
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //生成token
        //返回token客户端
        //用户信息缓存redis
        String username = authentication.getName();
        loginAttemptService.loginSucceeded(username);
        // 登录成功后重置失败计数

        Object principal = authentication.getPrincipal();
        if(principal instanceof SecurityUserDTO){
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setId(dto.getUserDO().getId());
            tokenDTO.setUsername(dto.getUsername());
            tokenDTO.setAvatarPath(dto.getUserDO().getAvatarPath());
            tokenDTO.setEmail(dto.getUserDO().getEmail());
            tokenDTO.setPhone(dto.getUserDO().getPhone());

            String token = JwtUtil.getToken(tokenDTO);
            // 用户信息缓存到redis中
            cacheManager.set(dto.getUsername(),dto,24, TimeUnit.HOURS);
            // 返回到客户端
            LoginResultVO loginResultVo = ConvertUtil.convert(dto,LoginResultVO.class);
            loginResultVo.setToken(token);
            Result<LoginResultVO> result = Result.buildSuccess(loginResultVo);
            ResponseUtil.respAppJson(response,result);
        }

    }
}
